package com.kis.bot.utils.api

import com.kis.bot.enums.StringEnums
import com.kis.bot.model.WeChat
import com.squareup.okhttp.FormEncodingBuilder
import com.squareup.okhttp.OkHttpClient
import com.squareup.okhttp.Request
import java.awt.Desktop
import java.io.File
import java.io.FileOutputStream
import java.util.*

/**
 * Created by wongloong on 16-8-31.
 */
object LoginApi {
    fun getUuid(): String {
        System.setProperty("jsse.enableSNIExtension", "false")
        var uuid: String
        val client = OkHttpClient()
        val form = FormEncodingBuilder()
        form.add("appid", StringEnums.APPID.value)
        form.add("fun", "new")
        form.add("lang", "zh_CN")
        val request = Request.Builder()
                .url(StringEnums.GETUUIDURL.value)
                .post(form.build())
                .addHeader("User-agent", StringEnums.USERAGENT.value)
                .build()

        val response = client.newCall(request).execute()
        if (response.isSuccessful) {
            val uuidString = response.body().string()
            println(uuidString)
            uuid = uuidString.split("\"")[1]
        } else {
            println("服务器错误${response}")
            uuid = ""
        }
        return uuid;
    }

    fun createQrCode(obj: WeChat) {
        System.setProperty("jsse.enableSNIExtension", "false")
        obj.uuid = getUuid()
        val client = OkHttpClient()
        val form = FormEncodingBuilder()
        form.add("t", "webwx")
        form.add("_", Date().time.toString())
        val request = Request.Builder()
                .url(StringEnums.SCANURL.value + "/" + obj.uuid)
                .post(form.build())
                .addHeader("User-agent", StringEnums.USERAGENT.value)
                .build()
        val response = client.newCall(request).execute()
        if (response.isSuccessful) {
            val pic = response.body().byteStream()
            val qrCode = File("${System.getProperty("user.dir")}/qr.jpeg")
            val output = FileOutputStream(qrCode)
            output.write(pic.readBytes())
            println("如图片没有显示，请在${System.getProperty("user.dir")}中查找qr.jpeg并扫描")
            var f = File("${System.getProperty("user.dir")}/qr.jpeg")
            Desktop.getDesktop().open(f)
        } else {
            println("服务器错误${response}")
        }
    }

    fun checkLogin(obj: WeChat, tip: Int = 1): Boolean {
        var result = false
        System.setProperty("jsse.enableSNIExtension", "false")
        val client = OkHttpClient()
        try {
            val request = Request.Builder()
                    .url(StringEnums.checkState.value + "&uuid=${obj.uuid}&tip=${tip}")
                    .get()
                    .addHeader("User-agent", StringEnums.USERAGENT.value).build()
            val response = client.newCall(request).execute()
            if (response.isSuccessful) {
                val body = response.body().string()
                println("登录body是:${body}")
                val code: String = body.split(";")[0].split("=")[1]
                when (code) {
                    "201" -> {
                        result = true
                    }
                    "200" -> {
                        obj.redirectUri = body.split(";")[1].split("window.redirect_uri=")[1].replace("\"", "")
                        obj.baseUri = obj.redirectUri.split("/webwxnew")[0]
                        result = true
                    }
                    "408" -> createQrCode(obj)
                    else -> result = false
                }
            }
        } catch (e: Exception) {
            checkLogin(obj)
        }
        return result
    }

    fun login(obj: WeChat): Boolean {
        System.setProperty("jsse.enableSNIExtension", "false")
        val client = OkHttpClient()
        val request = Request.Builder().url(obj.redirectUri + "&fun=new&version=v2").get()
                .addHeader("User-agent", StringEnums.USERAGENT.value).build()
        val response = client.newCall(request).execute()
        if (response.isSuccessful) {
            val dom = response.body().string()
            println(dom)
            obj.sKey = dom.getDomValue("skey")
            obj.uin = dom.getDomValue("wxuin")
            obj.sid = dom.getDomValue("wxsid")
            obj.pass_ticket = dom.getDomValue("pass_ticket")
        }
        if (obj.sKey.isNullOrEmpty() || obj.uin.isNullOrEmpty() ||
                obj.sid.isNullOrEmpty() || obj.pass_ticket.isNullOrEmpty()) {
            return false
        }
        obj.deviceId = "e".getDeviceId().toString()
//        obj.baseRequest = hashMapOf("Uin" to obj.uin, "Sid" to obj.sid, "Skey" to obj.sKey, "DeviceID" to obj.deviceId)
        return true
    }
}